<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use fast\lucn\Lucn;
use Endroid\QrCode\QrCode;

/**
 * 单页管理
 *
 * @icon fa fa-circle-o
 * @remark 用于管理普通的单页面,通常用于关于我们、联系我们、商务合作等单一页面
 */
class Review extends Backend
{

    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Review');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
			foreach($list as $i => $son){
			    $arr = json_decode($son['content'],true);
				$sales = isset($arr['销售区域']) ? $arr['销售区域'] : '';
				$guige = isset($arr['包装规格']) ? $arr['包装规格'] : '';
				$chuku = isset($arr['出库日期']) ? $arr['出库日期'] : '';
			    $list[$i]['sales'] = $sales;
				$list[$i]['guige'] = $guige;
				$list[$i]['chuku'] = $chuku;
			}
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
	
	private function edit_data($params,$has_field,$field,$value)
	{
	    if ($has_field == 1)
                {
                    //JSON字段
                    $fieldarr = $valuearr = [];
					$arr_field = array('content','place_record','farming_record','production_record','fertilizer_record','pesticides_record','testing_record');
					
					foreach($arr_field as $i => $son){
						if(isset($field[$son])){
						    foreach ($field[$son] as $k => $v)
						    {
						    if ($v != ''){
						        $fieldarr[] = $field[$son][$k];
			    			    $valuearr[] = $value[$son][$k];
						    }
					        }
							$params[$son] = json_encode(array_combine($fieldarr, $valuearr));
							//if(isset($field['content'])){file_put_contents("s:/test.txt",$valuearr);}
					        unset($fieldarr);unset($valuearr);
					    }else{
						    $params[$son] = '';
						}
                    }
					
                }
				
		 return $params;
				
	}
	/*
	public function add()
    {
        if ($this->request->isPost())
        {
            $this->code = -1;
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($this->request->has('field')){
				    $has_field = 1;
				}else{
				    $has_field = 0;
				}
				$field = $this->request->post('field/a');
                $value = $this->request->post('value/a');
                $params = $this->edit_data($params,$has_field,$field,$value);
				//dump($params);die;
                $this->model->save($params);
                $this->code = 1;
            }

            return;
        }
        return $this->view->fetch('review/edit');
    }
	
	public function edit($ids = NULL)
    {
	    $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $this->code = -1;
            $params = $this->request->post("row/a");
            if ($params)
            {
				if ($this->request->has('field')){
				    $has_field = 1;
				}else{
				    $has_field = 0;
				}
				$field = $this->request->post('field/a');
                $value = $this->request->post('value/a');
                $params = $this->edit_data($params,$has_field,$field,$value);
                $row->save($params);
                $this->code = 1;
            }

            return;
        }
		//dump($row);die;
		if(empty($row['content'])){
		    $row['content'] = '[]';
		}
        $this->view->assign("row", $row);
        return $this->view->fetch();
	}
	*/
	
	/**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                foreach ($params as $k => &$v)
                {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
					if ($this->request->has('field')){
				    $has_field = 1;
				        }else{
				    $has_field = 0;
				    }
				    $field = $this->request->post('field/a');
                    $value = $this->request->post('value/a');
                    $params = $this->edit_data($params,$has_field,$field,$value);
                    $result = $this->model->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch(Request::instance()->controller().'/edit');
    }
	
	/**
     * 编辑
     */
	public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                foreach ($params as $k => &$v)
                {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
					if ($this->request->has('field')){
				        $has_field = 1;
				    }else{
				        $has_field = 0;
				    }
				    $field = $this->request->post('field/a');
                    $value = $this->request->post('value/a');
					
                    $params = $this->edit_data($params,$has_field,$field,$value);
                    $result = $row->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
		//dump($row);die;
        return $this->view->fetch();
    }
	
	public function readcache()
	{
	    $cache = [];
		$cache['success'] = 1;
	    $cache['data']['basic_id'] = '0';
	    $cache['data']['bar_code'] = '1710270015';
		$cache['data']['product_name'] = '七芯黄花菜';
		$cache['data']['content']['出库日期'] = date('Y-m-d',time());
		$cache['data']['content']['销售区域'] = '';
		$cache['data']['content']['包装规格'] = '5公斤/箱';
		$cache['data']['note'] = date('Y-m-d',time());
		return json($cache);
	}
	
		// 生成二维码
    public function qrcode($ids = NULL)
    {   
		$row = $this->model->get($ids);
        if ($row){
		    $bar = $row['bar_code'];
			$filename = 'uploads/qrcode/'.$bar.'.png';
			$place = json_decode($row['content'],true)['销售区域'];
			$text = Request::instance()->domain().'/review-'.$bar;
			$size = '246';
			$padding = '54';
			$errorcorrection = 'medium';
			$foreground = "#ffffff";
            $background = "#000000";
			$logo = '1';
            $logosize = '45';
			$label = NULL;
			// 前景色
        list($r, $g, $b) = sscanf($foreground, "#%02x%02x%02x");
        $foregroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        // 背景色
        list($r, $g, $b) = sscanf($background, "#%02x%02x%02x");
        $backgroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        $qrCode = new QrCode();
        $qrCode
                ->setText($text)
                ->setSize($size)
                ->setPadding($padding)
                ->setErrorCorrection($errorcorrection)
                ->setForegroundColor($foregroundcolor)
                ->setBackgroundColor($backgroundcolor)
                ->setLogoSize($logosize)
                //->setLabelFontPath(ROOT_PATH . 'public/assets/fonts/fzltxh.ttf')
                //->setLabel($label)
                //->setLabelFontSize($labelfontsize)
                //->setLabelHalign($labelhalign)
                //->setLabelValign($labelvalign)
                ->setImageType(QrCode::IMAGE_TYPE_PNG);
        if ($logo)
        {
            $qrCode->setLogo('uploads/qrcode/logo.png');
        }
        //也可以直接使用render方法输出结果
        $qrCode->render('uploads/qrcode/temp.png');
		$image = \think\Image::open('uploads/qrcode/temp.png');
		$image->crop(354, 472,0,-118)->save('uploads/qrcode/temp.png');
		$image->water('uploads/qrcode/cpzs.png',\think\Image::WATER_NORTH)->save('uploads/qrcode/temp.png');
		$image->rotate(270)->save($filename);
		//rename('uploads/qrcode/'.$bar.'.png','/uploads/qrcode/'.$bar.'_'.iconv('UTF-8','GBK',$place).'.png');
		//return '<img src="/uploads/qrcode/'.$bar.'.png">';
		
// ob_start();
// $im = imagecreatefrompng($filename);
// imagepng($im);
// $file = ob_get_contents();
// ob_end_clean();
$file = file_get_contents($filename);

//数据块长度为9
$len = pack("N", 9);
//数据块类型标志为pHYs
$sign = pack("A*", "pHYs");
//X方向和Y方向的分辨率均为300DPI（1像素/英寸=39.37像素/米），单位为米（0为未知，1为米）
$data = pack("NNC", 300 * 39.37, 300 * 39.37, 0x01);
//CRC检验码由数据块符号和数据域计算得到
$checksum = pack("N", crc32($sign . $data));
$phys = $len . $sign . $data . $checksum;

$pos = strpos($file, "pHYs");
if ($pos > 0) {
	//修改pHYs数据块
	$file = substr_replace($file, $phys, $pos - 4, 21);
} else {
	//IHDR结束位置（PNG头固定长度为8，IHDR固定长度为25）
	$pos = 33;
	//将pHYs数据块插入到IHDR之后
	$file = substr_replace($file, $phys, $pos, 0);
}

header("Content-type: image/png");
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
echo $file;
		}
    }

}
